import { useState, useMemo, useEffect } from 'react';
import { Button, Empty, Input, Popconfirm, Space, Table, Tree, Modal, Form, Upload, message, Select, InputNumber, Checkbox, Progress } from "antd";
import { QuestionCircleFilled, LoadingOutlined } from '@ant-design/icons';
import { Key } from 'antd/es/table/interface';
// import MultilingualInput from '@inbiz/basic/MultilingualInput'
import moment from 'moment';
import { TextWidget, getMessage } from "@inbiz/react";
import { InbizIcon, getApp } from "@inbiz/utils";
// @ts-ignore
import Pagination from '@inbiz/basic/Pagination';
import { observer } from '@formily/react';
import AddModal from './component/AddModal';
import EditDrawer from './component/EditDrawer';
import { downLoadByUrl } from '@inbiz/render';
import { addFormGroup, deleteFormData, deleteFormGroup, editFormGroup, getAppList, getFormGroupData, getFormListData, importFormData } from './server';
import cnchar from 'cnchar';
import './index.less'

const { DirectoryTree } = Tree;
const { confirm } = Modal;

export interface FormManageProps {
  callBackEvents?: {
    onBeforeChange?: (v: string) => boolean;
  };
  emit?: {
    (type: 'ontest', arg: number, arg1: number): void;
  };
  className?: string;
  inbiz?: Function;
  allApps?: boolean;
  refs?: any;
  queryRegion?: string;
}

const FormManage = (props: FormManageProps) => {
  const {
    emit,
    inbiz,
    callBackEvents,
    className,
    allApps = props?.queryRegion == 'all' ? true : false,
    ...other
  } = props;
  // 分组数据
  const [groupData, $groupData] = useState<any[]>([])
  // 当前分组key
  const [activeGroup, $activeGroup] = useState<string>('')
  // 当前一级分组key
  const [activeGroup1, $activeGroup1] = useState<string>('')
  // 当前appId
  const [activeAppId, $activeAppId] = useState<string>(undefined)
  // 当前操作项的appId
  const [activeHandleAppId, $activeHandleAppId] = useState<string>(undefined)
  // 当前编辑应用内分组数据
  const [activeGroupData, $activeGroupData] = useState<any[]>([])
  // 当前选中应用内分组数据
  const [pickGroupData, $pickGroupData] = useState<any[]>([])
  // 添加/编辑分组弹窗显示
  const [addGroupVisible, $addGroupVisible] = useState<boolean>(false)
  // 编辑分组的信息
  const [editGroupInfo, $editGroupInfo] = useState<any>()
  // 导入弹窗显示
  const [visibleImport, $visibleImport] = useState<boolean>(false)
  // 表格的表单列表数据
  const [dataSource, $dataSource] = useState<any[]>([])
  // 表格数据加载loading
  const [loading, $loading] = useState<boolean>(false)
  // 搜索框值
  const [inputValue, $inputValue] = useState('');
  // 搜索文本
  const [searchText, $searchText] = useState<string>('');
  // 选择行id
  const [selectedRowKeys, $selectedRowKeys] = useState<any[]>([]);
  // 当前页数
  const [page, $page] = useState<number>(1);
  // 每页显示条数
  const [pageSize, $pageSize] = useState<number>(20);
  // 数据总数
  const [total, $total] = useState<number>(0)
  // 添加表单弹窗显示
  const [addFormVisible, $addFormVisible] = useState<boolean>(false)
  // 修改表单抽屉显示
  const [editFormVisible, $editFormVisible] = useState<boolean>(false)
  // 当前修改表单数据
  const [editFormData, $editFormData] = useState<any>()
  // 导入表单的本地文件数据流
  const [importFile, $importFile] = useState<any>(null);
  // 更新id
  const [updateId, $updateId] = useState<any>()
  // 是否初始化过
  const [inited, $inited] = useState<boolean>(false)
  // 分组树已展开的节点
  const [expandedKeys, $expandedKeys] = useState<string[]>([]);
  // 表单导入成功结果信息
  const [importResult, $importResult] = useState<any>()
  // 表单是否在导入中
  const [imported, $imported] = useState<boolean>(false)
  // 更新表单更新中
  const [updateLoading, $updateLoading] = useState<boolean>(false)
  // 新增/编辑分组弹窗表单
  const [form] = Form.useForm()
  // 更新是否覆盖
  const cover = Form.useWatch('cover', form)
  // 应用信息
  const appInfo = getApp()
  // 是否是组件预览
  const isPreview: boolean = !location.hash?.startsWith?.('#/b/form-manage')

  // 主体表格列
  const columns: any[] = [
    {
      title: getMessage('FormManage.form_name'),
      dataIndex: 'Name',
      width: 140,
      fixed: 'left',
      ellipsis: true,
      render: (txt: string) => {
        return <TextWidget>{txt}</TextWidget>;
      },
      onCell: (rec: any) => {
        return {
          title: getMessage(rec?.Name)
        }
      }
    },
    {
      title: getMessage('FormManage.current_version'),
      dataIndex: 'VersionNum',
      width: 100,
      ellipsis: true,
      render: (text: any) => {
        return text;
      },
    },
    {
      title: getMessage('FormManage.associated_process'),
      width: 100,
      ellipsis: true,
      dataIndex: 'WfName',
      render: (txt: string) => {
        return <TextWidget>{txt}</TextWidget>;
      },
      onCell: (rec: any) => {
        return {
          title: getMessage(rec?.WfName)
        }
      }
    },
    {
      title: getMessage('FormManage.remark'),
      dataIndex: 'Description',
      width: 200,
      ellipsis: true,
      render: (txt: string) => {
        return txt;
      },
    },
    {
      title: getMessage('FormManage.create_name'),
      dataIndex: 'CreatorName',
      width: 100,
      ellipsis: true,
      render: (txt: string, _: any) => {
        return _?.LastModificationName || txt;
      },
    },
    {
      title: getMessage('FormManage.createTime'),
      dataIndex: 'CreatorTime',
      width: 140,
      render: (createTime: any, _: any) => moment(_?.LastModificationTime || createTime).format('YYYY.MM.DD HH:mm'),
    },
    {
      title: getMessage('FormManage.operation'),
      dataIndex: 'operation',
      width: 220,
      fixed: 'right',
      render: (td: any, record: any) => (
        <Space
          size="middle"
          align="start"
          onClick={(e: any) => {
            e.preventDefault();
            e.stopPropagation();
          }}
        >
          {/* 设置 */}
          <Button
            type='link'
            style={{ padding: 0 }}
            onClick={() => {
              editForm(record)
            }}
          >
            <TextWidget>FormManage.set</TextWidget>
          </Button>
          {/* 设计 */}
          <Button
            type='link'
            style={{ padding: 0 }}
            onClick={() => {
              design(record);
            }}
          >
            <TextWidget>FormManage.design</TextWidget>
          </Button>
          {/* 更新 */}
          <Button
            type='link'
            style={{ padding: 0 }}
            onClick={() => {
              renew(record);
            }}
          >
            <TextWidget>FormManage.renew</TextWidget>
          </Button>
          {/* 删除 */}
          <Popconfirm
            title={getMessage('FormManage.comfirm_del')}
            onConfirm={() => delForm(record)}
            placement="topRight"
            okText={getMessage('FormManage.okText')}
            cancelText={getMessage('FormManage.cancelText')}
          >
            <Button type='link' style={{ padding: 0 }}><TextWidget>FormManage.del</TextWidget></Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 初始化
  useEffect(() => {
    allApps ?
      getAppData() :
      getGroupData()
  }, [allApps])

  // 分组变化更新表单表格数据
  useEffect(() => {
    if (activeGroup) {
      getFormData(1, pageSize)
    } else {
      $dataSource([])
    }
    $page(1)
    $selectedRowKeys([])
    $inputValue('')
    $searchText('')
  }, [activeGroup])

  // 当前操作分组变化同步筛选编辑弹窗的分组数据
  useEffect(() => {
    $activeGroupData(groupData?.find?.((i: any) => i.OutId == activeHandleAppId)?.Children || [])
  }, [groupData, activeHandleAppId])

  // 当前选中分组变化同步新建、编辑表单弹窗的分组数据
  useEffect(() => {
    $pickGroupData(groupData?.find?.((i: any) => i.OutId == activeAppId)?.Children || [])
  }, [groupData, activeAppId])

  // 获取所有应用
  const getAppData = () => {
    getAppList().then(async (res: any) => {
      if (Array.isArray(res?.Items) && res.Items.length) {
        const treeList: any[] = res.Items.map((i: any) => ({ ...i, OutId: i.Id, Name: i.AppName, app: true }))
        const nowGroup: any = await getFormGroupData({ appId: treeList[0]?.OutId })
        console.log('nowGroup', nowGroup)
        if (Array.isArray(nowGroup) && nowGroup.length) {
          $activeGroup(nowGroup?.[0]?.OutId || '')
          $activeGroup1(nowGroup?.[0]?.OutId || '')
          $activeAppId(nowGroup?.[0]?.AppId || undefined as string)
          $expandedKeys([treeList?.[0]?.OutId])
          const tree: any[] = nowGroup.map((item: any) => {
            return {
              ...item,
              Children: item?.Children?.filter((v: any) => v?.IsGroup)
            }
          })
          treeList[0].Children = tree
        } else {
          treeList[0].Children = []
        }
        $groupData(treeList)
      }
    })
  }

  // 获取分组数据-应用内
  const getGroupData = (appId?: string) => {
    getFormGroupData({
      appId: appId || appInfo?.AppId
    }).then((res: any) => {
      if (allApps) {
        // 全局
        $groupData((pre: any[]) => {
          return pre.map((i: any) => {
            if (i.OutId == appId) {
              return {
                ...i,
                Children: Array.isArray(res) ?
                  res.map((item: any) => {
                    return {
                      ...item,
                      Children: item?.Children?.filter((v: any) => v?.IsGroup)
                    }
                  }) : []
              }
            }
            return i
          })
        })
      } else {
        // 应用内
        if (Array.isArray(res)) {
          const tree: any[] = res.map((item: any) => {
            return {
              ...item,
              Children: item?.Children?.filter((v: any) => v?.IsGroup)
            }
          })
          $groupData(tree)
        } else {
          $groupData([])
        }
      }
      $inited(true)
    })
  }

  // 获取表单列表数据
  const getFormData = (idx: number, size: number, txt?: string) => {
    $loading(true)
    getFormListData({
      parentId: activeGroup,
      searchText: txt ?? searchText,
      isAll: false,
      skipCount: (idx - 1) * size,
      maxResultCount: size,
      appId: activeAppId
    }).then((res: any) => {
      if (Array.isArray(res?.Data)) {
        $total(res.Total)
        $selectedRowKeys([])
        $dataSource(res.Data)
        /* 表单名取消多语言后-取消前端分页 */
        // let data = res.Data.splice((idx - 1) * size, size)
        // data = data.filter((i: any) => getMessage(i?.Name)?.includes?.(txt ?? searchText))
        // $dataSource(data)
      } else {
        /** 接口请求失败清空数据 */
        $total(0)
        $selectedRowKeys([])
        $dataSource([])
      }
      $loading(false)
    })
  }

  // 新建分组
  const addGroup = (rec?: any) => {
    $activeHandleAppId(rec?.OutId || undefined)
    $editGroupInfo(null)
    $addGroupVisible(true)
    form.setFieldsValue({
      parent: allApps ? rec?.Children?.[0]?.OutId || undefined : activeGroup1 || undefined
    })
  }

  // 修改分组
  const editGroup = (rec: any) => {
    $activeHandleAppId(rec?.AppId || undefined)
    $editGroupInfo(rec)
    $addGroupVisible(true)
    form.setFieldsValue({
      groupName: rec.Name,
      route: rec.Route,
      parent: rec.ParentId,
      sort: rec.Sort
    })
  }

  // 新建表单
  const addForm = () => {
    $addFormVisible(true)
  }

  // 修改表单
  const editForm = (rec: any) => {
    $editFormData(rec)
    $editFormVisible(true)
    $activeHandleAppId(rec?.AppId)
  }

  // 删除表单
  const delForm = (rec?: any) => {
    const list = rec ? [rec.OutId] : selectedRowKeys
    const fn = () => {
      deleteFormData({
        outIds: list,
        appId: activeAppId
      }).then((res: any) => {
        if (res?.status) {
          message.success(getMessage('FormManage.del_mess'))
          refreshList(list.length)
        }
      })
    }
    if (rec) {
      fn()
    } else {
      confirm({
        title: getMessage('FormManage.comfirm_del'),
        okText: getMessage('FormManage.okText'),
        cancelText: getMessage('FormManage.cancelText'),
        // @ts-ignore
        icon: <QuestionCircleFilled />,
        centered: true,
        okType: 'danger',
        onOk: () => fn(),
        onCancel() { },
      });
    }
  }

  // 导出表单
  const exportForm = () => {
    confirm({
      title: getMessage('FormManage.export_mess'),
      // @ts-ignore
      icon: <QuestionCircleFilled />,
      content: null,
      centered: true,
      width: '372px',
      bodyStyle: { padding: '31px 17px 19px 20px' },
      okText: getMessage('FormManage.okText'),
      cancelText: getMessage('FormManage.cancelText'),
      onOk() {
        let strIds = selectedRowKeys.join(',')
        try {
          const url = `/inbiz/api/services/wfpage/v3/wfPage/export?pageOutIds=${strIds}`;
          downLoadByUrl(url, `Form${new Date().valueOf()}.zip`, activeAppId);
        } catch (err: any) {
          message.error(err)
        }
      },
    });
  }

  // 根据appId查应用路由
  const findDomain = (id: string) => {
    if (allApps) {
      return groupData?.find?.((i: any) => i.OutId == id)?.Domain
    } else {
      return appInfo?.App?.Domain
    }
  }

  // 设计表单
  const design = (rec: any) => {
    let url = ''
    const domain = findDomain(rec.AppId)
    if (process.env.NODE_ENV == 'development') {
      url = location.origin + '/' + domain + '?isform=true&formid=' + rec.OutId + '#/editor/' + rec.Route
    } else {
      url = `${location.origin}/inbiz/web/editor/${domain}?isform=true&formid=${rec.OutId}#/${rec.Route}`
    }
    window.open(url)
  }

  // 更新表单
  const renew = (rec: any) => {
    $updateId(rec.OutId)
    $visibleImport(true)
  }

  // 表格-筛选表单数据
  const filterForm = (txt: string) => {
    $searchText(txt)
    $page(1)
    getFormData(1, pageSize, txt)
  }

  // 表格-点当前行任意地方可选中
  const onSelectRow = (record: any) => {
    const selectedList = [...selectedRowKeys];
    if (selectedList.indexOf(record.OutId) >= 0) {
      //当点击选中的数据，取消选中
      selectedList.splice(selectedList.indexOf(record.OutId), 1);
    } else {
      //选中的数据放入数组
      selectedList.push(record.OutId);
    }
    $selectedRowKeys(selectedList);
  };

  // 表格-刷新表单列表数据
  const refreshList = (num?: number) => {
    let current = page
    /* 当删除或修改当前数据分组后当前页数据可能已经没有了-计算没有数据时显示上一页 */
    if (current > 1 && num && (total <= (page - 1) * pageSize + num)) {
      current = current - 1
      $page((pre: number) => pre - 1)
    }
    getFormData(current, pageSize)
  }

  // 分组点击
  const clickGroup = (key: Key, e: any) => {
    if (!e?.node?.app) {
      $activeGroup(key as string)
      $activeGroup1(e?.node?.ParentId || e?.node?.OutId || '' as string)
      $activeAppId(e?.node?.AppId || undefined as string)
    }
  }

  // 删除分组
  const delGroup = (rec: any) => {
    if (rec?.Children?.length != 0) {
      return message.warning(getMessage('FormManage.warn_del_group'))
    }
    confirm({
      title: getMessage('FormManage.define_delete_group'),
      // @ts-ignore
      icon: <QuestionCircleFilled />,
      centered: true,
      okText: getMessage('FormManage.okText'),
      cancelText: getMessage('FormManage.cancelText'),
      okType: 'danger',
      onOk() {
        return new Promise((resolve) => {
          deleteFormGroup({ outId: rec.OutId, dataVersionId: rec.DataVersionId, appId: rec?.AppId }).then((res: any) => {
            if (res?.status) {
              if (allApps) {
                onLoadData({ key: rec?.AppId }, rec.OutId == activeGroup, activeGroup == activeGroup1)
              } else {
                getGroupData(rec?.AppId)
              }
              message.success(getMessage('FormManage.del_mess'))
            }
            resolve(true)
          })
        })
      },
      onCancel() { },
    })
  };

  // 分组新增/编辑表单提交
  const groupSubmit = () => {
    form.validateFields().then((res: any) => {
      if (editGroupInfo && typeof editGroupInfo != 'string') {
        if (editGroupInfo?.ParentId != res.parent && editGroupInfo?.Children?.length)
          return message.warning(getMessage('FormManage.edit_group2_mess'))
        // 编辑
        editFormGroup({
          outId: editGroupInfo?.OutId,
          name: res.groupName?.trim?.(),
          parentId: res.parent,
          sort: res.sort,
          appId: editGroupInfo?.AppId
        }).then((res: any) => {
          if (res?.OutId) {
            message.success(getMessage('FormManage.edit_group_mess'))
            if (allApps) {
              onLoadData({ key: editGroupInfo?.AppId })
            } else {
              getGroupData(editGroupInfo?.AppId)
            }
          }
        })
      } else {
        // 新增
        addFormGroup({
          name: res.groupName,
          route: res.route,
          parentId: res.parent,
          sort: res.sort,
          appId: activeHandleAppId
        }).then((res: any) => {
          if (res?.OutId) {
            message.success(getMessage('FormManage.add_group_mess'))
            if (allApps) {
              onLoadData({ key: activeHandleAppId }, activeGroup == '', activeGroup == '')
            } else {
              getGroupData(activeHandleAppId)
            }
          }
        })
      }
      $expandedKeys((pre: string[]) => {
        const s = [...pre]
        if (!pre.includes(res.parent)) {
          s.push(res.parent)
        }
        if (allApps && !pre.includes(activeHandleAppId)) {
          s.push(activeHandleAppId)
        }
        return s
      })
      $editGroupInfo(null)
      $addGroupVisible(false)
      form.resetFields()
    })
  }

  // 导入/更新表单提交
  const importSubmit = () => {
    form.validateFields().then((data: any) => {
      const formData = new FormData()
      formData.append('file', importFile)
      formData.append('groupId', activeGroup)
      // @ts-ignore
      formData.append('cover', Boolean(data.cover))
      if (updateId) {
        formData.append('formOutId', updateId)
      } else if (data.cover) {
        // @ts-ignore
        formData.append('overwrite', Boolean(data.overwrite))
      }
      if (!updateId) {
        $imported(true)
      } else {
        $updateLoading(true)
      }
      importFormData(formData, activeAppId).then((res: any) => {
        if (Array.isArray(res.Success)) {
          // 提示
          const mess: string = getMessage(updateId ? 'FormManage.update_success' : 'FormManage.import_success')
          if (updateId) {
            // 关闭弹窗
            $visibleImport(false)
            $importFile(null)
            $updateLoading(false)
            // 初始化
            $updateId(null)
            form.resetFields()
            message.success(mess, updateId ? 3 : 6)
          } else {
            $importResult(res)
          }
          refreshList()
        } else {
          $importResult({
            Cover: [],
            Fail: [],
            Skip: [],
            Success: []
          })
          $updateLoading(false)
          if (updateId) {
            message.success('FormManage.update_false')
          }
        }
      })
    })
  }

  // 分组树单项节点Dom
  const TreeNode = (rec: any) => {
    return (
      <div className='custon-tree-node'>
        <span title={getMessage(rec.Name)}>
          <TextWidget>{rec.Name}</TextWidget>
        </span>
        <Space className='tree-node-hand' onClick={(e) => { e.stopPropagation() }}>
          {/* 添加 */}
          {
            rec?.app ? <InbizIcon
              type="icon-ic-add-bold"
              onClick={() => { addGroup(rec) }}
            /> : null
          }
          {/* 修改 */}
          {
            rec?.app ? null : <InbizIcon
              type="icon-ic-bianjituandui"
              onClick={() => { editGroup(rec) }}
            />
          }
          {/* 删除-系统分组不允许删除 */}
          {
            rec.IsSystem || rec?.app ? null :
              <InbizIcon
                className='del'
                type="icon-ic-shanchu1"
                onClick={() => { delGroup(rec) }}
              />
          }
        </Space>
      </div>
    )
  }

  // 自动计算后的tree数据
  const treeData = useMemo(() => {
    /* 如没有选中分组-选中第一个 */
    if (!activeGroup) {
      if (allApps) {
        $activeGroup(groupData?.[0]?.Children?.[0]?.OutId || '')
        $activeGroup1(groupData?.[0]?.Children?.[0]?.OutId || '')
        $activeAppId(groupData?.[0]?.Children?.[0]?.AppId || undefined)
      } else {
        $activeGroup(groupData?.[0]?.OutId || '')
        $activeGroup1(groupData?.[0]?.OutId || '')
        $activeAppId(groupData?.[0]?.AppId || undefined)
      }
    }
    return groupData.map((item: any) => {
      let i = {
        ...item,
        title: TreeNode(item)
      }
      if (i.Children?.length) {
        i.Children = i.Children.map((val: any) => {
          let j = {
            ...val,
            isLeaf: (allApps && val.Children?.length) ? false : true,
            title: TreeNode({ ...val, parent: item.OutId }),
          }
          if (allApps && j.Children?.length) {
            j.Children = j.Children.map((rec: any) => {
              return {
                ...rec,
                isLeaf: true,
                title: TreeNode({ ...rec, parent: item.OutId }),
              }
            })
          }
          return j
        })
      }
      return i
    })
  }, [groupData, activeGroup, activeGroup1, activeAppId])

  // 中文转拼音
  const cnTochare = (name: string) => {
    let route = cnchar.spell(getMessage(name)?.replaceAll(' ', '')) as string;
    route = route.toLowerCase();
    // @ts-ignore
    route = route.replaceAll('ü', 'v');
    return route
  }

  // 表单变化监听
  const onValuesChange = (info: any) => {
    if (editGroupInfo && typeof editGroupInfo != 'string') return
    if (info.groupName) {
      info.route = cnTochare(info.groupName)
      form.setFieldsValue(info);
    }
    if (info.route) {
      info.route = info.route.toLowerCase();
      form.setFieldsValue(info);
    }
  }

  // 树展开节点变化
  const onExpand = (keys: string[]) => {
    $expandedKeys(keys);
  };

  // 异步加载树节点的子节点(获取指定应用下分组列表)
  const onLoadData = ({ key, Children }: any, pick?: boolean, top?: boolean) => {
    return new Promise<void>(async (resolve) => {
      const selGroup = (nowGroup: any) => {
        if (pick) {
          // 重选当前分组
          if (Array.isArray(nowGroup) && nowGroup.length) {
            if (top) {
              $activeGroup(nowGroup?.[0].OutId || '')
              $activeGroup1(nowGroup?.[0].OutId || '')
              $activeAppId(nowGroup?.[0].AppId || undefined)
            } else {
              const find = nowGroup.find((i: any) => i.OutId == activeGroup1)?.Children
              if (find?.length) {
                $activeGroup(find?.[0].OutId || '')
              } else {
                $activeGroup(activeGroup1)
              }
            }
          } else {
            $activeGroup('')
            $activeGroup1('')
            $activeAppId(undefined)
          }
        }
      }
      const nowGroup: any = await getFormGroupData({ appId: key })
      const tree = treeData.map((i: any) => {
        if (i.OutId == key) {
          selGroup(nowGroup)
          if (Array.isArray(nowGroup) && nowGroup.length) {
            return { ...i, Children: nowGroup }
          } else {
            return { ...i, Children: [] }
          }
        }
        return i
      })
      $groupData(tree)
      resolve();
    });
  }

  // 判断导入是否有成功的
  const checkResult = (res: any, bool?: boolean) => {
    if (!res) {
      return 'active'
    } else {
      if (res?.Cover?.length || res?.Fail?.length || res?.Skip?.length || res?.Success?.length) {
        return bool ? false : 'success'
      }
      return bool ? true : 'exception'
    }
  }

  return (
    <>
      <div className="inbiz-comp-form-manage">
        {/* 左侧内容 */}
        <div className="left-content">
          {/* 头部Header */}
          {allApps ? null : <div className="left-header">
            {/* 分组列表 */}
            <span><TextWidget>FormManage.group_Title</TextWidget></span>
            <div className="add-group-btn" onClick={addGroup}>
              <span>
                <InbizIcon type="icon-ic-tianjia-moren" />
              </span>
              <span style={{ marginLeft: '8px' }}>
                <TextWidget>FormManage.add</TextWidget>
              </span>
            </div>
          </div>}
          {/* 分组树 */}
          <div className='group-tree'>
            {
              groupData?.length ?
                <DirectoryTree
                  showIcon={false}
                  fieldNames={{
                    key: 'OutId',
                    children: 'Children',
                  }}
                  expandedKeys={expandedKeys}
                  onExpand={onExpand}
                  loadData={allApps ? onLoadData : null}
                  onSelect={(keys: Key[], e: any) => clickGroup(keys?.[0] || '', e)}
                  selectedKeys={activeGroup !== '' ? [activeGroup] : []}
                  treeData={treeData}
                /> :
                inited ? <Empty
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  description={<TextWidget>FormManage.no_data</TextWidget>}
                /> : null
            }
          </div>
        </div>
        {/* 右侧内容 */}
        <div className="right-content">
          {/* 按钮部分 */}
          <div className="buttons-header">
            <Space size="middle">
              {/* 新建 */}
              <Button
                type="primary"
                onClick={addForm}
                disabled={!activeGroup}
              >
                <InbizIcon type="icon-ic-tianjia" />
                <TextWidget>FormManage.new_add</TextWidget>
              </Button>
              {/* 删除 */}
              <Button onClick={() => delForm()} danger disabled={!selectedRowKeys.length}>
                <InbizIcon type="icon-shanchu-h" />
                <TextWidget>FormManage.del</TextWidget>
              </Button>
              {/* 导入 */}
              <Button onClick={() => $visibleImport(true)} disabled={!activeGroup}>
                <InbizIcon type="icon-daoru" />
                <TextWidget>FormManage.import</TextWidget>
              </Button>
              {/* 导出 */}
              <Button onClick={exportForm} disabled={!selectedRowKeys.length}>
                <InbizIcon type="icon-daochu" />
                <TextWidget>FormManage.derive</TextWidget>
              </Button>
            </Space>
            <Input
              style={{ width: 200 }}
              placeholder={getMessage('FormManage.searchPlaceholder')}
              suffix={
                <InbizIcon
                  type="icon-mokuai-tongyisousuoyinqing"
                  onClick={() => filterForm(inputValue)}
                />
              }
              onPressEnter={(e: any) => {
                filterForm(e.target.value);
              }}
              onChange={(e: any) => $inputValue(e.target.value)}
              value={inputValue}
            />
          </div>
          <div className="table-list">
            <Table
              rowKey="OutId"
              dataSource={dataSource}
              loading={loading}
              columns={columns}
              className={isPreview ? '' : 'b-form-manage-table'}
              scroll={{ x: 1000, y: 800 }}
              size="middle"
              bordered
              rowSelection={{
                selectedRowKeys,
                columnWidth: '40px',
                onChange: (newSelectedRowKeys: any, record: any) => {
                  $selectedRowKeys(newSelectedRowKeys);
                },
              }}
              onRow={(record) => ({
                onClick: () => onSelectRow(record),
              })}
              pagination={false}
            />
            <Pagination
              refreshData={() => {
                refreshList();
              }}
              pageRefresh={true}
              pagination={{
                current: page,
                pageSize: pageSize,
                total: total,
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: [10, 20, 30, 50, 100],
                showLessItems: true,
                // @ts-ignore
                showTotal: true,
              }}
              onPageChange={({ current, pageSize }) => {
                $page(current);
                $pageSize(pageSize);
                getFormData(current, pageSize)
              }}
            />
          </div>
        </div>
        {/* 添加/修改分组弹窗 */}
        <Modal
          title={
            (editGroupInfo && typeof editGroupInfo != 'string')
              ? getMessage('FormManage.edit_group')
              : getMessage('FormManage.add_group')
          }
          visible={addGroupVisible}
          onCancel={() => {
            $editGroupInfo(null)
            $addGroupVisible(false)
            form.resetFields()
          }}
          onOk={groupSubmit}
          wrapClassName="form-manage-add-group-modal"
          width={450}
          okText={getMessage('FormManage.okText')}
          cancelText={getMessage('FormManage.cancelText')}
          centered={true}
          destroyOnClose
        >
          <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 19 }} onValuesChange={onValuesChange}>
            {/* 分组名称 */}
            <Form.Item
              name='groupName'
              label={getMessage('FormManage.add_group_name')}
              required
              rules={[
                ({ }) => ({
                  validator(_, value): any {
                    if (!value || value?.trim?.() == '') {
                      return Promise.reject(new Error(getMessage('FormManage.enter_group_name')))
                    } else if (value.length > 50) {
                      return Promise.reject(getMessage('FormManage.limit_group_length'))
                    } else if (/^[\u4E00-\u9FA5A-Za-z0-9\_\-\——\'\(\)\。\、\【\】\‘\’\“\”\《\》\……\（\）\s]+$/.test(value)) {
                      /* 暂时去掉对语言支持 */
                      // } else if (/^[\u4E00-\u9FA5A-Za-z0-9\_\-\——\'\(\)\。\、\【\】\‘\’\“\”\《\》\……\（\）\s]+$/.test(value.replace('.i18n', '').replace('{multilingual}', ''))) {
                      return Promise.resolve()
                    }
                    return Promise.reject(getMessage('FormManage.special_character'))
                  },
                }),
              ]}
            >
              <Input
                placeholder={getMessage('FormManage.please_input')}
              />
            </Form.Item>
            {/* 分组标识 */}
            <Form.Item
              name='route'
              label={getMessage('FormManage.add_group_key')}
              rules={[
                { required: true, message: getMessage('FormManage.key_quest') },
                {
                  pattern: /^[a-zA-Z0-9_-]*$/,
                  message: getMessage('FormManage.key_check'),
                },
                {
                  pattern: /^.{2,50}$/,
                  message: getMessage('FormManage.key_long'),
                }
              ]}
            >
              <Input placeholder={getMessage('FormManage.please_input')} disabled={editGroupInfo && typeof editGroupInfo != 'string'} />
            </Form.Item>
            {/* 父级分组 */}
            <Form.Item
              name='parent'
              label={getMessage('FormManage.add_group_group')}
            >
              <Select
                allowClear
                placeholder={getMessage('FormManage.please_sele')}
                showSearch
                virtual={false}
                optionFilterProp="label"
                filterOption={(input, option) => {
                  if (typeof option?.title == 'string') {
                    return (option?.title ?? '')?.toLowerCase().includes(input.toLowerCase())
                  } else {
                    return false
                  }
                }}
                disabled={(editGroupInfo && typeof editGroupInfo != 'string') && editGroupInfo.IsSystem}
              >
                {
                  (allApps ? activeGroupData : groupData)?.map?.((item: any) => {
                    return (
                      <Select.Option
                        value={item.OutId}
                        key={item.OutId}
                        title={getMessage(item.Name)}
                        disabled={(editGroupInfo && typeof editGroupInfo != 'string') && editGroupInfo.OutId == item.OutId}
                      >
                        <TextWidget>{item.Name}</TextWidget>
                      </Select.Option>
                    )
                  })
                }
              </Select>
            </Form.Item>
            {/* 分组排序 */}
            <Form.Item
              name='sort'
              label={getMessage('FormManage.add_group_sort')}
            >
              <InputNumber
                placeholder={getMessage('FormManage.please_input')}
                min={0}
                style={{ width: '100%' }}
              />
            </Form.Item>
          </Form>
        </Modal>
        {/* 导入/更新表单弹窗 */}
        <Modal
          title={updateId ? getMessage('FormManage.update') : getMessage('FormManage.import')} // 更新 : 导入
          visible={visibleImport}
          onCancel={() => {
            $visibleImport(false)
            $updateId(null)
            $importFile(null)
            form.resetFields()
            $imported(false)
            $importResult(null)
          }}
          width={450}
          wrapClassName="form-manage-import-modal"
          okText={getMessage('FormManage.okText')}
          centered={true}
          destroyOnClose
          style={imported ? { position: 'absolute', top: 50, transform: 'translateX(-50%)' } : {}}
          footer={imported ? null : [
            <Button onClick={() => {
              $visibleImport(false)
              $updateId(null)
              $importFile(null)
              form.resetFields()
            }}
            >
              <TextWidget>FormManage.cancelText</TextWidget>
            </Button>,
            <Button
              type='primary'
              onClick={importSubmit}
              loading={updateId ? updateLoading : false}
            >
              <TextWidget>FormManage.okText</TextWidget>
            </Button>
          ]}
        >
          {
            /** 导入进度情况 */
            imported ? <>
              <p>
                {importResult ? checkResult(importResult, true) ? <><TextWidget>FormManage.importFiled</TextWidget>{'：'}</> : '' : <><TextWidget>FormManage.importing</TextWidget>{'：'}</>}
                {importFile?.name}
                {!importResult && <LoadingOutlined style={{ marginLeft: 5 }} />}
              </p>
              {/* @ts-ignore */}
              <Progress percent={importResult ? 100 : 10} status={checkResult(importResult)} />
              <p style={{ paddingBottom: 30, paddingTop: 15 }}>
                {/* 导入成功 */}
                {
                  importResult?.Success?.length ? <>
                    <span>
                      <TextWidget>FormManage.import_succ</TextWidget>
                      {
                        importResult.Success.map((i: string) => (`【${i}】`))
                      }
                      <TextWidget>FormManage.form</TextWidget>
                    </span>
                  </> : null
                }
                {/* 覆盖 */}
                {
                  importResult?.Cover?.length ? <>
                    <span>
                      <TextWidget>FormManage.covered</TextWidget>
                      {
                        importResult.Cover.map((i: string) => (`【${i}】`))
                      }
                      <TextWidget>FormManage.form</TextWidget>
                    </span>
                  </> : null
                }
                {/* 跳过 */}
                {
                  importResult?.Skip?.length ? <>
                    <span>
                      <TextWidget>FormManage.skiped</TextWidget>
                      {
                        importResult.Skip.map((i: string) => (`【${i}】`))
                      }
                      <TextWidget>FormManage.form</TextWidget>
                    </span>
                  </> : null
                }
                {/* 失败 */}
                {
                  importResult?.Fail?.length ? <>
                    <span>
                      <TextWidget>FormManage.fail</TextWidget>
                      {
                        importResult.Fail.map((i: string) => (`【${i}】`))
                      }
                      <TextWidget>FormManage.form</TextWidget>
                    </span>
                  </> : null
                }
              </p>
            </> :
              /** 添加导入文件表单 */
              <Form form={form} style={{ paddingTop: 10 }}>
                <Form.Item
                  name="fileName"
                  label={getMessage('FormManage.form_file')}
                  labelCol={{ span: 5 }}
                  wrapperCol={{ span: 19 }}
                  rules={[{ required: true, message: getMessage('FormManage.please_sele_file') }]}
                >
                  {/* accept限制文件类型 */}
                  <div className='form-manage-import-box'>
                    <div className='import-content'>
                      <Input
                        value={importFile != null ? importFile.name : ''}
                        id="fileName"
                        autoComplete="off"
                        style={{ marginRight: '8px' }}
                        onChange={() => {
                          let timer = setTimeout(() => {
                            form.resetFields(['fileName'])
                            clearTimeout(timer)
                          }, 0)
                        }}
                      />
                      <Upload
                        accept=".xml,.zip"
                        showUploadList={false}
                        onRemove={(file) => {
                          $importFile(null);
                        }}
                        beforeUpload={(file) => {
                          const whiteType = ['application/x-zip-compressed', 'application/zip', 'text/xml'];
                          if (!whiteType.includes(file.type)) {
                            message.error(getMessage('FormManage.format_mismatch'));
                            let timer = setTimeout(() => {
                              form.resetFields(['fileName'])
                              clearTimeout(timer)
                            }, 0)
                            $importFile(null);
                            return false;
                          }
                          const isLt10M = file.size / 1024 / 1024 < 10;
                          if (!isLt10M) {
                            message.error(getMessage('FormManage.file_size'));
                            let timer = setTimeout(() => {
                              form.resetFields(['fileName'])
                              clearTimeout(timer)
                            }, 0)
                            $importFile(null);
                            return false;
                          }
                          return $importFile(file);
                        }}
                        fileList={importFile ? [importFile] : []}
                      >
                        <Button type="primary">
                          <TextWidget>FormManage.select</TextWidget>
                        </Button>
                      </Upload>
                    </div>
                  </div>
                </Form.Item>
                <Form.Item
                  name='cover'
                  label={getMessage('FormManage.can_update')}
                  valuePropName="checked"
                  labelCol={{ span: 5 }}
                  wrapperCol={{ span: 19 }}
                >
                  <div>
                    <Checkbox />
                    <span className='update-placeholder'><TextWidget>{updateId ? 'FormManage.update_message' : 'FormManage.import_message'}</TextWidget></span>
                  </div>
                </Form.Item>
                {
                  !updateId && cover && <Form.Item
                    name='overwrite'
                    valuePropName="checked"
                    wrapperCol={{ span: 19, offset: 5 }}
                    style={{ marginTop: -20 }}
                  >
                    <div>
                      <Checkbox />
                      <span className='update-placeholder'><TextWidget>FormManage.update_message</TextWidget></span>
                    </div>
                  </Form.Item>
                }
              </Form>
          }
        </Modal>
        {/* 添加表单弹窗 */}
        <AddModal
          visible={addFormVisible}
          $visible={$addFormVisible}
          refresh={refreshList}
          groupData={allApps ? pickGroupData : groupData}
          activeGroup={activeGroup}
          addGroup={addGroup}
          design={design}
          activeAppId={activeAppId}
        />
        {/* 设置抽屉 */}
        <EditDrawer
          visible={editFormVisible}
          $visible={$editFormVisible}
          record={editFormData}
          groupData={allApps ? pickGroupData : groupData}
          refresh={refreshList}
          design={design}
          activeAppId={activeAppId}
          findDomain={findDomain}
        />
      </div >
    </>
  );
}
export default observer(FormManage);
